package app.Service;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import common.result.CodeEnum;
import common.result.ResponseResult;
import common.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class Mailservice {
    @Autowired
    RedisUtils redisUtils;

    /**
     * 创建邮件html内容
     *
     * @param captcha 验证码
     * @return html文本
     */
    public String getmsg(int captcha) {
        String fileContent;
        fileContent = " <div>\n" +
                "        <div>cuiter点评验证码服务</div>\n" +
                "        <div>\n" +
                "            <p><b>亲爱的用户，你好！</b></p>\n\n" +
                "            <div>\n" +
                "                <div>\n" +
                "                    <p><b>您的的验证码：</b><span style=\"border-bottom: 1px dashed rgb(204, 204, 204); z-index: 1; position: static;\">" + captcha + "(请输入该验证码完成验证，验证码2分钟内有效！)</span></p>\n" +
                "                    <div>如果你未操作cuiter点评相关服务，请忽略该邮件。</div>\n" +
                "                </div>\n" +
                "            </div>\n" +
                "        </div>\n" +
                "    </div>";
        return fileContent;
    }

    /**
     * 发送邮件，封装邮件内容返回
     *
     * @param mailaccount 用户邮箱地址
     * @return
     */
    public ResponseResult sendMail(String mailaccount) {
        MailAccount account = new MailAccount();
        account.setHost("smtp.163.com");
        account.setPort(465);
        account.setAuth(true);
        account.setFrom("hannibal_mail@163.com");
        account.setUser("hannibal_mail@163.com");
        account.setPass("FOSGDUPTXBXEEWVQ");
        account.setSslEnable(true);
        int captcha = (int) (Math.random() * 1000000);
        String content = getmsg(captcha);
        System.out.println(content);
        MailUtil.send(account, CollUtil.newArrayList(mailaccount),
                "验证服务", content, true);
        //将验证码存到redis里面用于验证,key是邮箱账号 value是验证码 过期时间为120s
        redisUtils.set(mailaccount, String.valueOf(captcha), 120L, TimeUnit.SECONDS);
        return new ResponseResult(CodeEnum.SUCCESS.getCode(), CodeEnum.SUCCESS.getMessage());
    }
}